#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
日志管理模块
提供操作日志的显示和管理功能
"""

import tkinter as tk
from tkinter import ttk
import datetime
import threading


class Logger:
    def __init__(self, parent, height=16):
        """
        初始化日志器

        Args:
            parent: 父容器
            height: 文本框高度（行数）
        """
        self.parent = parent
        self.height = height
        self.text_widget = None
        self.progress_var = None
        self.progress_label = None

        self.create_widgets()

    def create_widgets(self):
        """创建日志显示组件"""
        # 创建滚动条
        scrollbar = ttk.Scrollbar(self.parent)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        # 创建文本框
        self.text_widget = tk.Text(
            self.parent,
            height=self.height,
            wrap=tk.WORD,
            yscrollcommand=scrollbar.set,
            state=tk.DISABLED
        )
        self.text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.config(command=self.text_widget.yview)

        # 设置标签样式
        self.text_widget.tag_configure("info", foreground="black")
        self.text_widget.tag_configure("success", foreground="green")
        self.text_widget.tag_configure("warning", foreground="orange")
        self.text_widget.tag_configure("error", foreground="red")
    def log(self, message, level="info"):
        """添加日志消息"""
        def add_log():
            self.text_widget.config(state=tk.NORMAL)
            
            # 获取当前时间
            timestamp = datetime.datetime.now().strftime("%H:%M:%S")
            
            # 添加时间戳和消息
            self.text_widget.insert(tk.END, f"[{timestamp}] ", "info")
            self.text_widget.insert(tk.END, f"{message}\n", level)
            
            # 自动滚动到底部
            self.text_widget.see(tk.END)
            self.text_widget.config(state=tk.DISABLED)
            
        # 确保在主线程中更新UI
        if threading.current_thread() is threading.main_thread():
            add_log()
        else:
            self.parent.after(0, add_log)

    def clear(self):
        """清空日志"""
        self.text_widget.config(state=tk.NORMAL)
        self.text_widget.delete(1.0, tk.END)
        self.text_widget.config(state=tk.DISABLED)

    def info(self, message):
        """信息日志"""
        self.log(message, "info")

    def success(self, message):
        """成功日志"""
        self.log(message, "success")

    def warning(self, message):
        """警告日志"""
        self.log(message, "warning")

    def error(self, message):
        """错误日志"""
        self.log(message, "error")